package bjut.zrpc.core.optimization.loadbalance;

import bjut.zrpc.core.optimization.factory.SingletonFactory;
import bjut.zrpc.core.optimization.message.ZRpcRequestMessage;

import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Author: zhuzhiming
 * @Date: 2022/6/28 17:16
 */

public class PollLoadBalance extends AbstractLoadBalance {

    private static final ConcurrentHashMap<String, Integer> POLL_SERVICE_MAP = new ConcurrentHashMap<>();

    @Override
    protected String doSelect(List<String> serviceList, ZRpcRequestMessage zRpcRequestMessage) {

        serviceList.sort(String::compareTo);
        String serviceInfo = zRpcRequestMessage.getServiceInfo();
        Integer position = POLL_SERVICE_MAP.get(serviceInfo);
        position = position == null || position > serviceList.size() - 1 ? 0 : position;
        String service = serviceList.get(position);
        POLL_SERVICE_MAP.put(serviceInfo, ++position);
        return service;

    }
}
